package com.beeasy.hzbpm.bean;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.github.llyb120.json.Obj;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.IOException;
import java.io.InputStream;

public class JsEngine {
    public static final ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("javascript");
    private static String lib;


    static {
        ClassPathResource resource = new ClassPathResource("lib.js");
        try(InputStream is = resource.getStream()){
            lib = IoUtil.read(is, CharsetUtil.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String buildExpression(Obj attrs, String expression){
        expression = expression.replaceAll("“|”", "\"")
            .replaceAll("‘|’","'");
        StringBuilder sb = new StringBuilder();
        sb.append("(function(){\n");
        sb.append("var data = ");
        sb.append(attrs.toString());
        sb.append(";\n");
        sb.append(lib);
        sb.append("return ");
        sb.append(expression);
        sb.append("})()");
        return sb.toString();
    }

    public static String calExpression(Obj attrs, String expression){
        try{
            return String.valueOf(jsEngine.eval(buildExpression(attrs, expression)));
        } catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    public static boolean runExpression(Obj attrs, String expression){
        if(StrUtil.isBlank(expression)){
            return true;
        }
        expression = buildExpression(attrs, expression);
        try{
            return (boolean) jsEngine.eval(expression);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
